package ui.commodity;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.table.DefaultTableModel;

import client.boot.BLServiceManager;
import blservice.client.ClientBLService;
import blservice.commodity.CommodityBLService;
import blservice.document.DocumentBLService;
import tool.MyButton;
import tool.MyLabel;
import vo.CommodityVo;
import vo.StockSendingDocumentVo;
import vo.ClientVo;
import vo.UserVo;
import vo.Vo;

import java.awt.Font;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.awt.Color;

public class StockSendDocumentPanel extends JPanel {
	private static final long serialVersionUID = 1L;

	List<StockSendingDocumentVo> vo;
	UserVo user;
	private JTable table;
	private JScrollPane jsp;
	private JTextField number;
	private JTextField operator;
	private boolean isNew;
	private boolean editable;
	private JComboBox<String> client;
	private List<CommodityVo> commodities;
	private boolean 审批;
	private boolean 红冲;

	/**
	 * 
	 * @param user
	 * @param vo
	 *            如果是单据查询，则传入vo，如果是单据制定则传入null;
	 * @param editable
	 *            如果是新建或者红冲并复制就设置成editable
	 * @param 红冲 
	 */
	public StockSendDocumentPanel(UserVo user, StockSendingDocumentVo vo, boolean editable,boolean 审批, boolean 红冲) {
		this.红冲=红冲;
		this.审批=审批;
		this.user = user;
		this.setLayout(null);
		this.setOpaque(false);
		this.editable = editable;
		this.vo = new ArrayList<StockSendingDocumentVo>();
		if (vo == null) {
			isNew = true;
		} else {
			isNew = false;
			this.vo.add(vo);
		}
		JLabel label = new JLabel("库存赠送单");
		label.setForeground(Color.WHITE);
		label.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		label.setBounds(273, 10, 93, 21);
		add(label);

		JLabel label_1 = new MyLabel("\u5355\u636E\u7F16\u53F7\uFF1A");
		label_1.setBounds(47, 53, 75, 15);
		add(label_1);

		JButton add = new MyButton("Graphics/Button45-23.png");
		add.setText("+");
		add.setBounds(465, 96, 45, 23);
		if (!editable) {
			add.setVisible(false);
		}
		add.addActionListener(e -> addLine());
		add(add);

		JLabel label_4 = new MyLabel("业务员：");
		label_4.setForeground(Color.WHITE);
		label_4.setBounds(370, 53, 54, 15);
		add(label_4);

		JButton submit = new MyButton("Graphics/Button93-23.png");
		submit.setText("\u63D0\u4EA4");
		submit.setBounds(489, 383, 93, 23);
		submit.addActionListener(e -> submit());
		if (!editable&&!审批&&!红冲) {
			submit.setVisible(false);
		}
		if(审批){
			submit.setText("通过审批");
		}
		if(红冲){
			submit.setText("红冲");
		}
		add(submit);

		JButton sub = new MyButton("Graphics/Button45-23.png");
		sub.setText("-");
		sub.setBounds(537, 96, 45, 23);
		sub.addActionListener(e -> subLine());
		if (!editable) {
			sub.setVisible(false);
		}
		add(sub);

		table = new JTable() {
			private static final long serialVersionUID = 3028897666676861555L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return editable;
			}
		};
		table.setBounds(47, 128, 535, 248);
		jsp = new JScrollPane(table);
		jsp.setBounds(47, 128, 535, 248);
		jsp.setVisible(true);
		this.add(jsp);

		number = new JTextField();
		number.setEditable(false);
		number.setColumns(10);
		number.setBounds(122, 50, 105, 21);
		add(number);

		operator = new JTextField();
		operator.setEditable(false);
		operator.setColumns(10);
		operator.setBounds(429, 50, 105, 21);
		if (isNew) {
			operator.setText(user.getName());
		} else {
			operator.setText(vo.get业务员());
		}
		add(operator);

		client = new JComboBox<String>();
		client.setBounds(122, 78, 105, 21);
		add(client);

		JLabel label_2 = new MyLabel("客户：");
		label_2.setBounds(47, 81, 54, 15);
		add(label_2);
		
		iniClient();
		iniCommodity();
		
		displayTable();
	}

	void displayTable() {
		if(!isNew){
			number.setText(vo.get(0).get单据编号());
			operator.setText(vo.get(0).get业务员());
		}
		DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] { "商品", "赠送数量", "备注" });

		for (StockSendingDocumentVo o : vo) {
			model.addRow(new String[] {
					o.get商品编号() + ":" + o.get商品名称() + "." + o.get商品型号(),
					Integer.toString(o.getNum()), o.get备注() });
		}
		if (editable) {
			model.addRow(new String[] { "", "", "" });
		}
		table.setModel(model);
		if (editable) {
			JComboBox<String> temp = new JComboBox<String>();
			for (CommodityVo o : commodities) {
				temp.addItem(o.get编号() + ":" + o.getName() + "." + o.get型号());
			}
			table.getColumnModel().getColumn(0)
					.setCellEditor(new DefaultCellEditor(temp));
		}
	}

	void saveTable() {
		List<StockSendingDocumentVo> items = vo;
		items.clear();
		for (int i = 0; i < table.getRowCount(); i++) {
			StockSendingDocumentVo temp = new StockSendingDocumentVo();
			temp.set单据编号(number.getText());
			temp.set备注((String) table.getValueAt(i, 2));
			if(((String) table.getValueAt(i, 0)).indexOf(":")==-1||((String) table.getValueAt(i, 0)).indexOf(".")==-1){
				continue;
			}
			temp.set商品编号(((String) table.getValueAt(i, 0)).substring(0,((String) table.getValueAt(i, 0)).indexOf(":")));
			if(((String) table.getValueAt(i, 0)).indexOf(":")+1<((String) table.getValueAt(i, 0)).length())
				temp.set商品名称(((String) table.getValueAt(i, 0)).substring(((String) table.getValueAt(i, 0)).indexOf(":")+1,((String) table.getValueAt(i, 0)).indexOf(".")));
			if(((String) table.getValueAt(i, 0)).indexOf(".")+1<((String) table.getValueAt(i, 0)).length())
				temp.set商品型号(((String) table.getValueAt(i, 0)).substring(((String) table.getValueAt(i, 0)).indexOf(".")+1));
			boolean successed = false;
			try {
				int tempMoney = Integer.parseInt((String) table
						.getValueAt(i, 1));
				temp.setNum(tempMoney);
				successed = true;
			} catch (NumberFormatException e) {
			}
			if (successed) {
				items.add(temp);
			}
		}
	}

	void subLine() {
		int line = table.getSelectedRow();
		if (line == -1 || line >= vo.size()) {
			return;
		} else {
			vo.remove(line);
			displayTable();
		}
	}

	void addLine() {
		saveTable();
		displayTable();
	}

	void submit() {
		saveTable();
		displayTable();
		if (vo.size() == 0) {
			JOptionPane.showMessageDialog(this, "请填写赠送列表\n");
			return;
		}
		DocumentBLService bl;
		try {
			bl = BLServiceManager.load库存赠送单BLService(null);
			//把添加过的从vo中remove掉，这里是一个缓冲，避免移除造成序号错误
			ArrayList<Integer> removing=new ArrayList<Integer>();
			for (int i=0;i<vo.size();i++) {
				vo.get(i).setOperator(user.getName());
				vo.get(i).setOperation("库存赠送");
				vo.get(i).set业务员(user.getName());
				vo.get(i).set客户((String) client.getSelectedItem());
				Vo result;
				if(审批){
					result=bl.approve(vo.get(i));
					if (result.isSuccessed()) {
						JOptionPane.showMessageDialog(this, "单据提交成功\n");						
					} else {
						JOptionPane.showMessageDialog(this,
								"单据提交失败\n" + result.getFailMessage());
					}
					break;
				}else if(红冲&&!editable){
					result=bl.redRush(vo.get(i));
					if (result.isSuccessed()) {
						JOptionPane.showMessageDialog(this, "单据提交成功\n");						
					} else {
						JOptionPane.showMessageDialog(this,
								"单据提交失败\n" + result.getFailMessage());
					}
					break;
				}else if(红冲&&editable){
					result=bl.redRushAndCopy(vo.get(i));
					if (result.isSuccessed()) {
						JOptionPane.showMessageDialog(this, "单据提交成功\n");						
					} else {
						JOptionPane.showMessageDialog(this,
								"单据提交失败\n" + result.getFailMessage());
					}
					break;
				}else{				
					result = bl.add(vo.get(i));
				}
				if (result.isSuccessed()) {
					JOptionPane.showMessageDialog(this, "单据提交成功\n");
					if(i<vo.size()&&i>=0)
						removing.add(i);
					
				} else {
					JOptionPane.showMessageDialog(this,
							"单据提交失败\n" + result.getFailMessage());
				}
			}

			removing.sort(new Comparator<Integer>() {
				@Override
				public int compare(Integer o1, Integer o2) {
					return o1-o2;
				}
				
			});
			for(int i=removing.size()-1;i>=0;i--){
				vo.remove((int)removing.get(i));
			}
		} catch (RemoteException | MalformedURLException | SQLException
				| NotBoundException e) {
			JOptionPane.showMessageDialog(this, "无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
		displayTable();
	}

	void iniClient() {
		if (isNew) {
			try {
				ClientBLService clientBL = BLServiceManager
						.getClientBLService(null);
				List<ClientVo> clientList = clientBL.getAll();
				DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
				for (ClientVo o : clientList) {
					model.addElement(o.get姓名());
				}
				client.setModel(model);

			} catch (RemoteException | MalformedURLException
					| NotBoundException | SQLException e) {
				JOptionPane.showMessageDialog(this,
						"无法连接到服务器\n" + e.getMessage());
				e.printStackTrace();
			}
		} else {
			DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
			model.addElement(vo.get(0).get客户());
			client.setModel(model);
			client.setEnabled(false);
		}
	}
	
	void iniCommodity(){
		try {
			CommodityBLService bl=BLServiceManager.getCommodityBLService(null);
			commodities=bl.getAll();
		} catch (RemoteException | MalformedURLException | NotBoundException
				| SQLException e) {
			JOptionPane.showMessageDialog(this,
					"无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
		
	}
}
